//
//  OAWebViewController.m
//  OAMobile
//
//  Created by 李天露 on 2018/1/12.
//  Copyright © 2018年 李天露. All rights reserved.
//

#import "OAWebViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "UIImage+Helper.h"
#import "NSData+Helper.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "OAConfigVC.h"
#import "XDShareView.h"
#import <MessageUI/MessageUI.h>
#import "WebViewJavascriptBridge.h"
#import "SDWebImageDownloader.h"
#import "UIImageView+WebCache.h"
#import <AlipaySDK/AlipaySDK.h>

@interface OAWebViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,UIAlertViewDelegate,MFMessageComposeViewControllerDelegate>

@property (nonatomic, strong) JSContext* context;
@property (nonatomic, strong) XDShareView *shareview;
@property (nonatomic, strong) NSDictionary *shareData;

#ifdef DEBUG
@property (nonatomic, strong) UILabel *environmentLabel;
@property (nonatomic, strong) UISwitch* environmentSW;
@property (nonatomic, strong) UIButton* configBtn;
#endif

@end

@implementation OAWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(MessageUIEvent:) name:@"MessageUI" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToAd:) name:@"pushtoad" object:nil];
#ifdef DEBUG
    
    self.configBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-75, 25, 60, 30)];
    self.configBtn.layer.cornerRadius = 5;
    self.configBtn.layer.masksToBounds = YES;
    self.configBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.configBtn.titleLabel setTextColor:[UIColor redColor]];
    [self.configBtn setTitle:@"配置" forState:UIControlStateNormal];
    self.configBtn.backgroundColor = [UIColor lightGrayColor];
    [self.configBtn addTarget:self action:@selector(touchEvent) forControlEvents:UIControlEventTouchDown];
    //[self.view addSubview:self.configBtn];
    
    self.environmentLabel = [[UILabel alloc] initWithFrame:CGRectMake(12, SCREEN_HEIGHT - 50, 80, 31)];
    self.environmentLabel.layer.borderColor = RGB(64, 150, 238).CGColor;
    self.environmentLabel.layer.borderWidth = 1.0;
    self.environmentLabel.layer.cornerRadius = 4;
    self.environmentLabel.text = @"正式环境";
    self.environmentLabel.textAlignment = NSTextAlignmentCenter;
    self.environmentLabel.font = [UIFont systemFontOfSize:15];
    self.environmentLabel.textColor = RGB(64, 150, 238);
    [self.view addSubview:self.environmentLabel];
    
    UISwitch* environmentSW = [[UISwitch alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.environmentLabel.frame)+10, SCREEN_HEIGHT - 50, 51, 31)];
    self.environmentSW = environmentSW;
    [environmentSW setOnTintColor:UIColorFromRGB(0x4095EF, 1.0)];    [environmentSW addTarget:self action:@selector(_environmentSW:) forControlEvents:UIControlEventValueChanged];
    NSString* env = [[NSUserDefaults standardUserDefaults] objectForKey:@"environment"];
    [environmentSW setOn:[env isEqualToString:@"production"]];
    [self.view addSubview:environmentSW];

#endif
    [self shareEvent];
    self.webView.scrollView.bounces = NO;
}
-(void)shareEvent{
    __weak typeof(self) weakSelf = self;
    [self.bridge registerHandler:@"smshare" handler:^(id data, WVJBResponseCallback responseCallback) {
        __strong typeof(self) strongSelf = weakSelf;
        [strongSelf.view addSubview:strongSelf.shareview];
        [strongSelf.shareview shareViewShow];
        strongSelf.shareview.shareData = [NSDictionary dictionaryWithDictionary:data];
        NSLog(@"testObjcCallback called: %@", data);
        responseCallback(@"Response from testObjcCallback");
    }];
    [self.bridge registerHandler:@"smpop" handler:^(id data, WVJBResponseCallback responseCallback) {
        __strong typeof(self) strongSelf = weakSelf;
        [strongSelf.navigationController popToRootViewControllerAnimated:YES];
    }];
    [self.bridge registerHandler:@"smSaveImg" handler:^(id data, WVJBResponseCallback responseCallback) {
        __strong typeof(self) strongSelf = weakSelf;
        //NSString *imgPath = [data objectForKey:@"path"];
        //[strongSelf saveImageToLocal:imgPath];
        
        [strongSelf savaImgOfBase64:[data objectForKey:@"base64"]];
        
    }];
}
#ifdef DEBUG
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [super webView:webView didFailLoadWithError:error];
    [self.view bringSubviewToFront:self.configBtn];
}

-(void)touchEvent{
    OAConfigVC *vc = [[OAConfigVC alloc] init];
    [self presentViewController:vc animated:YES completion:nil];
    
}
#endif
//环境切换
- (void)_environmentSW:(UISwitch*)sw {
    if (sw.on == YES) {
        [[NSUserDefaults standardUserDefaults] setObject:@"production" forKey:@"environment"];
    }else {
        [[NSUserDefaults standardUserDefaults] setObject:@"development" forKey:@"environment"];
    }
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    [super webViewDidFinishLoad:webView];
    
#ifdef DEBUG
    NSRange range = [webView.request.URL.absoluteString rangeOfString:@"login"];
    if (range.location == NSNotFound) {
        self.environmentSW.hidden = YES;
        self.environmentLabel.hidden = YES;
    }
#endif
    
     //对JSContext对象进行初始化
     self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
     //验证JSContext对象是否初始化成功
     self.context.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue)
     {
         context.exception = exceptionValue;
     };
    
     WEAKSELF
     self.context[@"openNativeComponent"] = ^(){
         NSLog(@"currentThread == %@",[NSThread currentThread]);
         NSArray *args = [JSContext currentArguments];
         JSValue *jsVal = [args firstObject];
         NSString *type= [jsVal toString];
//         if ([type isEqualToString:@"1"]) {
//             [weakSelf showImageActionSheet];
//         }
     };
    
    
}


- (BOOL)isCaptureDeviceauthorization {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
        
        //无权限
        return NO;
        
    }else
        return YES;
}

#pragma mark -- 打开相机
- (void)showImageActionSheet
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (![self isCaptureDeviceauthorization]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示"message:@"请到设置->隐私->相机服务中开启相机服务" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置",nil];
            
            [alert show];
        }else {
            [self takePhoto];
        }
    });
}


- (void)pushToAd:(NSNotification*)notify{
    NSString *url = [notify.userInfo objectForKey:@"clickUrl"];
    OAWebViewController *vc = [[OAWebViewController alloc] initWithTitle:@"" url:url];
    [self.navigationController pushViewController:vc animated:YES];
}
//打开照相机拍照
-(void)takePhoto {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: sourceType]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
//    if (buttonIndex == 1) {
//        NSURL *url1 = [NSURL URLWithString:@"prefs:root=Privacy"];
//        // iOS10也可以使用url2访问，不过使用url1更好一些，可具体根据业务需求自行选择
//        NSURL *url2 = [NSURL URLWithString:@"App-Prefs:root=Privacy"] ;
//
//        if (@available(iOS 10.0, *)) {
//            if ([[UIApplication sharedApplication] canOpenURL:url2]){
//                [[UIApplication sharedApplication] openURL:url2 options:@{} completionHandler:nil];
//            }
//        } else {
//            if ([[UIApplication sharedApplication] canOpenURL:url1]){
//                if (@available(iOS 10.0, *)) {
//                    [[UIApplication sharedApplication] openURL:url1 options:@{} completionHandler:nil];
//                } else {
//                    [[UIApplication sharedApplication] openURL:url1];
//                }
//            }
//        }
//    }
}

//照相的代理
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSData* imageData = [UIImage compressImageQualityWithImage:image toByte:0.5 * 1024 * 1024];
        
        [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"cameraDone('%@');",[imageData base64EncodedString]]];
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}
-(XDShareView *)shareview{
    if(!_shareview){
        _shareview = [[XDShareView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT)];
    }
    return _shareview;
}

-(void)dealloc {
    self.webView.delegate = nil;
    [self.webView stopLoading];
    [self.webView removeFromSuperview];
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark -- js function
-(void)smShare:(NSDictionary *)dic{
    
}

#pragma mark -- messageUI delegate

-(void)MessageUIEvent:(NSNotification*)notify{
    if (![MFMessageComposeViewController canSendText]) {
        return;
    }
    
    MFMessageComposeViewController *messageVC = [[MFMessageComposeViewController alloc]init];
    //短信内容
    messageVC.body = @"https://uat.healthstarknx.com/hestar-vue/InvitePartners";
    //短信收件人
    //messageVC.recipients = @[@"10086",@"10010"];
    //MFMessageComposeViewConreoller的代理
    messageVC.messageComposeDelegate = self;
    [self.shareview shareViewhidden];
    [self presentViewController:messageVC animated:YES completion:nil];
}
#pragma mark -- message ui delegate
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark -- save image to local
-(void)saveImageToLocal:(NSString*)imgPath{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //下载图片
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgPath]];
        UIImage *image = [UIImage imageWithData:data];
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    });
}

-(void)savaImgOfBase64:(NSString *)base64String{
    // Base64形式的字符串为data
    NSData *data = [[NSData alloc] initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
    // 图片数据
    UIImage *image = [[UIImage alloc] initWithData:data];
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSString *alertString;
    if (error) {
        alertString = @"图片保存失败";
    } else {
        alertString = @"图片保存成功";
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:alertString preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}
@end
